<html>
	<head>
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
		<script type="text/javascript" src="FlickrPrivacySettingsRetriever.js"></script>
		<script type="text/javascript">
var extensionRequestResponse = null;

chrome.extension.onRequest.addListener(
	function(request, sender, sendResponse) {
		extensionRequestResponse = null;
		if (request.showPageAction) {
			if (sender.tab) {
				chrome.pageAction.show(sender.tab.id);
				updatePageAction(sender.tab.id);
			}
			// no response to this
			sendResponse();
			return;
		}
		if (request.photoIds) {
			if (sender.tab && sender.tab.url) {
				extensionRequestResponse = sendResponse;
				getUserId(sender.tab.url);
				return;
			}
			// not a valid URL
			sendResponse();
			return;
		}
	});

chrome.pageAction.onClicked.addListener(function(tab) {
	chrome.tabs.sendRequest(tab.id, { toggleShowingMode: true }, function() { updatePageAction(tab.id) });
});

function updatePageAction(tabId) {
	chrome.tabs.sendRequest(tabId, { getShowingMode: true }, function(response) {
		chrome.pageAction.setTitle( { "tabId": tabId, title: "Showing: " + response} );
		// TODO: update pageAction icon
	});
}


// TODO: object-ize this so we can have one request sequence for each page, each canceled when page navigates away


var req = null;


function getUserId(url) {
	req = new XMLHttpRequest();
	req.open(
		"GET",
		"http://api.flickr.com/services/rest/?" +
			"method=flickr.urls.lookupUser" + "&" +
			"api_key=505e56e36e7e092435c28c45c26a91d9" + "&" +
			"url=" + url,
		true);
	req.onload = gotUserId;
	req.send(null);
}


function gotUserId() {
	var user = req.responseXML.getElementsByTagName("user");
	var id = user[0].getAttribute("id");
	console.debug("id = " + id);
	getPublicPhotos(id);
}


function getPublicPhotos(id) {
	req = new XMLHttpRequest();
	req.open(
		"GET",
		"http://api.flickr.com/services/rest/?" +
			"method=flickr.people.getPublicPhotos&" +
			"api_key=505e56e36e7e092435c28c45c26a91d9&" +
			"user_id=" + id,
		true);
	req.onload = returnPhotoIds;
	req.send(null);
}


function returnPhotoIds() {
	var photoPrivacySettings = { };
	var photos = req.responseXML.getElementsByTagName("photo");
	for (var i = 0, photo; photo = photos[i]; i++)
		photoPrivacySettings[photo.getAttribute("id")] = "public";
	if (extensionRequestResponse)
		extensionRequestResponse( photoPrivacySettings );
}

		</script>
	</head>
</html>	
